module PcrWebApps
  module Person
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def acts_as_person(options={})
        configuration = { :force_last_name => true,
                          :force_email => true}
        configuration.update(options) if options.is_a?(Hash)
        class_eval do
          validates_presence_of :first_name
          validates_presence_of :last_name if configuration[:force_last_name]
          validates_presence_of :email if configuration[:force_email]
          validates_length_of :auth_id, :maximum => 16, :allow_nil => true
          validates_length_of :initial, :maximum =>  8, :allow_nil => true
          validates_length_of :first_name, :within=>  2..64, :allow_nil => true
          validates_length_of :last_name,
                              :within => 2..64,
                              :unless => Proc.new{|x| (configuration[:force_last_name] ? x.last_name.nil? : x.last_name.blank?)}
          validates_format_of :email, 
                              :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                              :unless => Proc.new{|x| (configuration[:force_email] ? x.email.nil? : x.email.blank)}

          before_validation_on_create :tweak_lastname unless configuration[:force_last_name]
          before_validation_on_create :tweak_email unless configuration[:force_email]
          
          attr_accessible :first_name, :last_name, :initial, :email, :auth_id

          def full_name
            [@first_name, @initial, @last].compact.join(" ")
          end
private
          def tweak_lastname
            self.last_name = "" if last_name.nil?
          end
          def tweak_email 
            self.email = "" if email.nil?
          end
        end
      end

      def has_phone(options={})
        configuration = { :force => true }
        configuration.update(options) if options.is_a?(Hash)
        class_eval do
          validates_presence_of :phone_number if configuration[:force]
          validates_format_of :phone_number,
                              :with => /^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/,
                              #Conforms to NANP A-digit and D-digit requirements (ANN-DNN-NNNN). 
                              #Area Codes 001-199 are not permitted; 
                              #Central Office Codes 001-199 are not permitted.
                              :message => "is missing or invalid",
                              :allow_nil => true
        end
      end
    end
  end
end
